﻿using System.Threading.Tasks;
using System;
using Microsoft.EntityFrameworkCore;
using Oracle.ManagedDataAccess.Client;
using Microsoft.AspNetCore.Http;
using Simple.Services.System;
using Simple.Services.System.QHSEUser.Models;
using Simple.Services.System.QHSEViolationCategory.Models;

namespace Simple.Services;

public class QHSEViolationCategoryObsService
{
    private readonly SimpleDbContext _context;
    public QHSEViolationCategoryObsService(SimpleDbContext context)
    {
        _context = context;
    }
    public async Task<List<QHSEViolationCategoryObsModel>> GetAsync()
    {
        var violationObses = await _context.Set<QHSESysViolationCategoryObs>().ToListAsync();
        return MapperHelper.Map<List<QHSEViolationCategoryObsModel>>(violationObses);
    }

    public async Task<QHSEViolationCategoryObsPageResultModel> GetResult(QHSEViolationCategoryObsPageInputModel inputModel)
    {
        var violationCategory = await _context.Set<QHSESysViolationCategory>().FindAsync(inputModel.Id);
        var hses = new List<QHSESysViolationObserver>();
        if (violationCategory.Item == "其它" || violationCategory.Item == "其他")
        {
            hses = await _context.Set<QHSESysViolationObserver>().AsNoTracking().Where(u => u.Note == null).ToListAsync();
        }
        else
        {
            hses = await _context.Set<QHSESysViolationCategoryObs>()
                        .AsNoTracking()
                         .Join(_context.Set<QHSESysViolationObserver>(), vcObs => vcObs.ObsCode, Observer => Observer.Code2, (vcObs, Observer) => new { vcObs, Observer })
                         .Where(u => u.vcObs.Code == violationCategory.Code)
                         .Select(x => x.Observer).ToListAsync();
        }
        
        var obsModels = MapperHelper.Map<List<QHSEViolationObserverModel>>(hses);
        var resultModel = new QHSEViolationCategoryObsPageResultModel { Result = obsModels };
        return resultModel;
    }
}
